﻿using System;
using Castle.DynamicProxy;
using Turquoise.Caching.Abstract;
using Turquoise.Caching.Entities;
using Turquoise.Caching.Microsoft;

namespace Turquoise.Caching.Aspects.CastleWindsor
{

    public class CacheInterceptor : IInterceptor
    {
        private ICacheManager _cacheManager;

      
        public void Intercept(IInvocation invocation)
        {
            var attributes = Attribute.GetCustomAttribute(invocation.Method, typeof(TurquoiseCacheAttribute), false) as TurquoiseCacheAttribute;
            if (attributes != null)
            {
                if (invocation.Method.ReturnParameter == null)
                {
                    throw new Exception("geri dönüş parametresi olmayan bir methoda caching uygulanamaz");
                } 
                if (attributes.CacheKey == null)
                {
                   attributes.CacheKey  = invocation.InvocationTarget + "_" + invocation.Method.Name;
                }


                if (attributes.IsDistributed)
                {
              //      _cacheManager= new RedisCacheManager();
                }
                else
                {
                    _cacheManager = new MemoryCacheManager();
                }

                if (_cacheManager.Get(attributes.CacheKey) == null)
                {
                    invocation.Proceed();
                    _cacheManager.Add(attributes.CacheKey, invocation.ReturnValue);
                }
                else
                {
                    invocation.ReturnValue = _cacheManager.Get(attributes.CacheKey);
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
